﻿using Book.Books;
using Book.CreateUpdate_DTO;
using Book.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using Radis.Application.Caching;
using Microsoft.Extensions.Caching.Distributed;

namespace Book.AppService
{
    public class ShowService : ApplicationService, IShowService
    {
        public IRepository<Book, Guid> _repository;
        public IRepository<tbImg, Guid> _Img;
        public IDistributedCache Cache { get; set; }
        public IRepository<tbCommodityType, Guid> _Type;
        public IRepository<User, Guid> _User;
        private IRepository<tbOrderInfo, Guid> _order;
        private IRepository<tbSaleNum, Guid> _SaleNum;
        public ShowService(IRepository<tbCommodityType, Guid> Type, IRepository<Book, Guid> books, 
            IRepository<tbImg, Guid> Img, IRepository<User, Guid> User, IRepository<tbOrderInfo, Guid> orderInfos,
            IRepository<tbSaleNum, Guid> SaleNum)
        {
            _repository = books;
            _Img = Img;
            _Type = Type;
            _User = User;
            _order = orderInfos;
            _SaleNum = SaleNum;
        }
        [HttpPost, Route("取消订单，加库存")]
        public int CanCellation(string guid)
        {
            var list = _order.Where(s=>s.Id.ToString().Equals(guid)).FirstOrDefault();//获取到该订单信息表的信息
            list.OrderInfoAuditState = 50;//审核状态   50已取消
            list.OrderInfoState = 50;//订单状态  50取消订单
            _order.UpdateAsync(list);
            var info = _SaleNum.Where(s=>s.OrderInfoId.Equals(guid)).ToList();//查询当前订单下的商品信息
            foreach (var item in info)
            {

                //通过订单表中的商品id查询出该商品的信息
                var Commodity = _repository.Where(s=>s.Id.ToString().Equals(item.CommodityId)).FirstOrDefault();
                Commodity.ProductNum = Commodity.ProductNum + item.Num;//将数量加上购买数量
                _repository.UpdateAsync(Commodity);
            }
            
            return 1;//成功返回1；

        }
        //点击发货
        [HttpPost, Route("发货")]
        public int Shipments(string guid)
        {
            var list = _order.Where(s => s.Id.ToString().Equals(guid)).FirstOrDefault();//获取到该订单信息表的信息
           
            list.OrderInfoState = 30;//订单状态  30点击发货
            _order.UpdateAsync(list);
        

            return 1;//成功返回1；

        }
        //确认收货
        [HttpPost, Route("ConfirmReceipt确认收货")]
        public int ConfirmReceipt(string guid)
        {
            var list = _order.Where(s => s.Id.ToString().Equals(guid)).FirstOrDefault();//获取到该订单信息表的信息

            list.OrderInfoState = 40;//订单状态  40确认收货
            _order.UpdateAsync(list);


            return 1;//成功返回1；

        }



        [HttpGet]
        public List<OrderDTO> ShowOrder(int Type)
        {
            if (Type == -1)
            {
                var display = (from info in _order
                               join num in _SaleNum
                               on info.Id.ToString() equals num.OrderInfoId

                               select new OrderDTO()
                               {
                                   OrderInfoTime = info.OrderInfoTime,//下单日期
                                   PayWayInfoId = info.PayWayInfoId,//支付方式
                                   MemberId = info.MemberId,//客户id
                                   OrderInfoName = info.OrderInfoName,//收货人姓名
                                   ShoppAddreTel = info.ShoppAddreTel,//收货人电话
                                   OrderInfoSalePrice = info.OrderInfoSalePrice,//订单总金额
                                   OrderInfoBarCode = info.OrderInfoBarCode,//配送方式
                                   OrderWheShipments = info.OrderWheShipments,//是否发货
                                   OrderInfoAuditState = info.OrderInfoAuditState,//审核状态
                                   OrderInfoWhetherPay = info.OrderInfoWhetherPay,//是否支付
                                   OrderInfoState = info.OrderInfoState,//订单状态（已下单（未支付），待发货（已支付），已发货（待收货），已完成（已确认），订单取消（订单关闭））
                                   OrderInfoDeliveryState = info.OrderInfoDeliveryState,//配送状态
                                   CommodEvaluaOrder = info.CommodEvaluaOrder,//前台是否显示
                                   OrderInfoId = num.OrderInfoId,//订单号ID
                                   CommodityId = num.CommodityId,//商品id
                                   Price = num.Price,//价格(购买时)
                                   Num = num.Num,//销售数量
                                   Name = num.Name,//商品名称
                                   SmallImage = num.SmallImage,//商品图片

                               }).ToList();
                return display;
            }
            else
            {
                var display = (from info in _order
                               join num in _SaleNum
                               on info.Id.ToString() equals num.OrderInfoId
                               where info.OrderInfoState.Equals(Type)

                               select new OrderDTO()
                               {
                                   OrderInfoTime = info.OrderInfoTime,//下单日期
                                   PayWayInfoId = info.PayWayInfoId,//支付方式
                                   MemberId = info.MemberId,//客户id
                                   OrderInfoName = info.OrderInfoName,//收货人姓名
                                   ShoppAddreTel = info.ShoppAddreTel,//收货人电话
                                   OrderInfoSalePrice = info.OrderInfoSalePrice,//订单总金额
                                   OrderInfoBarCode = info.OrderInfoBarCode,//配送方式
                                   OrderWheShipments = info.OrderWheShipments,//是否发货
                                   OrderInfoAuditState = info.OrderInfoAuditState,//审核状态
                                   OrderInfoWhetherPay = info.OrderInfoWhetherPay,//是否支付
                                   OrderInfoState = info.OrderInfoState,//订单状态（已下单（未支付），待发货（已支付），已发货（待收货），已完成（已确认），订单取消（订单关闭））
                                   OrderInfoDeliveryState = info.OrderInfoDeliveryState,//配送状态
                                   CommodEvaluaOrder = info.CommodEvaluaOrder,//前台是否显示
                                   OrderInfoId = num.OrderInfoId,//订单号ID
                                   CommodityId = num.CommodityId,//商品id
                                   Price = num.Price,//价格(购买时)
                                   Num = num.Num,//销售数量
                                   Name = num.Name,//商品名称
                                   SmallImage = num.SmallImage,//商品图片

                               }).ToList();
                return display;
            }
         
        }


        //添加用户
        [HttpPost, Route("AddUser")]
        public async Task<UserDTO> AddUser(CreateUpdatetbUserDto adduser)
        {
            var infor = await _User.InsertAsync(ObjectMapper.Map<CreateUpdatetbUserDto, User>(adduser));
            return ObjectMapper.Map<User, UserDTO>(infor);
        }
        //添加订单
        [HttpPost,Route("AddOrder")]
        public async  Task<int> AddOrder(CreateUpdatetbOrderInfoDto dto)
        {
            var obj = new tbOrderInfo()
            {
                OrderInfoTime = DateTime.Now,
                PayWayInfoId = dto.PayWayInfoId,
                MemberId = dto.MemberId,
                OrderInfoAddre = dto.OrderInfoAddre,
                OrderInfoName = dto.OrderInfoName,
                ShoppAddreTel = dto.ShoppAddreTel,
                OrderInfoSalePrice = dto.OrderInfoSalePrice,
                CommodCountPrice = dto.CommodCountPrice,
                OrderInfoBarCode = dto.OrderInfoBarCode,
                OrderInfoPayPrice = dto.OrderInfoPayPrice,
                OrderInfoActiveName = dto.OrderInfoActiveName,
                OrderDiscount = dto.OrderDiscount,
                OrderPrivilPrice = dto.OrderPrivilPrice,
                OrderInfoActivePrice = dto.OrderInfoActivePrice,
                OrderInvoiceM = dto.OrderInvoiceM,
                OrderInfoState = 10,
                OrderInfoWaybillNum = dto.OrderInfoWaybillNum,
                LogComId = dto.LogComId,
                OrderWheShipments=dto.OrderWheShipments,
                OrderInfoAuditState=dto.OrderInfoAuditState,
                OrderInfoWhetherPay=dto.OrderInfoWhetherPay,
                OrderInfoDeliveryState=dto.OrderInfoDeliveryState,
                CommodEvaluaGrade=dto.CommodEvaluaGrade,
                CommodEvaluaTime=dto.CommodEvaluaTime,
                CommodEvaluaOrder=dto.CommodEvaluaOrder


            };
           await _order.InsertAsync(obj);
            List<tbSaleNum> tbSales = new List<tbSaleNum>();
            foreach (var item in dto.SaleNumDtos)
            {
                tbSales.Add(new tbSaleNum()
                {
                    OrderInfoId=obj.Id.ToString(),//订单编号
                    CommodityId=item.Id.ToString(),//商品编号
                    Price = item.Price,//价格(购买时)
                    Num = item.Num,//销售数量
                    Name = item.Name,//商品名称
                    SmallImage = item.SmallImage,//商品图片
                });
                var list = _repository.Where(s=>s.Id.ToString().Equals(item.Id.ToString())).FirstOrDefault(); //根据商品表id去找到商品详情表中循环中的商品外键id
                if (list.ProductNum == 0)
                {
                    return 2;//2是没库存了
                }
                list.ProductNum = list.ProductNum - item.Num;
                await _repository.UpdateAsync(list);

            }
            await _SaleNum.InsertManyAsync(tbSales);
            return 1;
            
           
        }
        [HttpGet,Route("GetListcommodity三表联查商品内容")]
        //三表联查
        public List<BookDTO> GetListcommodity()
        {
            var query = (from a in _repository
                         join b in _Img
                         on a.Id.ToString() equals b.PrimaryId
                         join c in _Type
                         on a.ProductTypeId equals c.Id.ToString()
                         select new BookDTO
                         {  
                             Id=a.Id,
                             ProductName=a.ProductName,
                             ProductSubtitle=a.ProductSubtitle,
                             ProductDisplay=a.ProductDisplay,
                             ProductSalePrice=a.ProductSalePrice,
                             ProductSPromotion=a.ProductSPromotion,
                             ProductWeight=a.ProductWeight,
                             ProductTypeId=c.Id.ToString(),
                             CommodTypeName=c.CommodTypeName,
                             ImgUrl=b.ImgUrl,
                             ImgMasterMap=b.ImgMasterMap,
                             ImgType=b.ImgType,
                             PrimaryId=a.Id.ToString()


                         }).ToList();
            return query;



        }

        [HttpPost]
        public async Task<tbImgDTO> Addimgurl(CreateUpdatetbImgDto dto)
        {
            var infor = await _Img.InsertAsync(ObjectMapper.Map<CreateUpdatetbImgDto, tbImg>(dto));
            return ObjectMapper.Map<tbImg, tbImgDTO>(infor);
        }
  

        [HttpGet,Route("商品列表")]
        public List<BookDTO> bookcontext()
        {
            var list = _repository.ToList();
            
            return ObjectMapper.Map<List<Book>, List<BookDTO>>(list);
        }

       

        [HttpGet, Route("图片显示")]
        public List<tbImgDTO> IMGshow()
        {
            var list = _Img.ToList();
            return ObjectMapper.Map<List<tbImg>, List<tbImgDTO>>(list);
        }
        //登录
        [HttpPost]
        public int Login(string username, string userpwd)
        {
            List<User> users = new List<User>();
            var login = _User.Where(s=>s.username.Equals(username)&&s.userpwd.Equals(userpwd)).ToList().Count();
            if (login > 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public string Upload(IFormFile File)
        {
            string rootdir = AppContext.BaseDirectory.Split(@"\bin\")[0];
            string fname = DateTime.Now.ToString("yyyyMMddHHmmssffff") + System.IO.Path.GetExtension(File.FileName);
            var path = rootdir + @"\Upload\" + fname;
            using (System.IO.FileStream fs = System.IO.File.Create(path))
            {
                File.CopyTo(fs);
                fs.Flush();//清空文件流
            }
            return "http://localhost:8015/" + fname;//将能访问新文件的网址回传给前端


        }
        //radis接口
        [HttpGet]
        public async Task<List<BookDTO>> GetProductList()
        {
            return await Cache.GetOrAddAsync("BookListByType",async () =>
                {
                    var lst = (from info in _repository
                               join type in _Type
                               on info.ProductTypeId equals (type.Id).ToString()
                               join img in _Img
                               on info.PrimaryId equals img.Id.ToString()
                               select new BookDTO()
                               {
                                   Id = info.Id,
                                   ProductTypeId = type.Id.ToString(),
                                   //商品名称
                                   ProductName = info.ProductName,
                                   //商品副名称
                                   ProductSubtitle = info.ProductSubtitle,
                                   //是否显示
                                   ProductDisplay = info.ProductDisplay,
                                   //商品数量‘
                                   ProductNum=info.ProductNum,
                                   //销售开始时间
                                   ProductSalePrice = info.ProductSalePrice,
                                   //销售价格(原价)
                                   ProductSPromotion = info.ProductSPromotion,
                                   //促销价格(商城价)
                                   ProductWeight = info.ProductWeight,
                                   PrimaryId = img.Id.ToString(),
                                   ImgUrl = img.ImgUrl

                               }).ToList();
                    return lst;
                },



            60
            );
            //TODO:后续如果有需要可以加缓存降级，即如果缓存中不存在主页楼层的数据，不去数据库中读，直接返回默认的楼层商品
        }
    }
}
